package com.hbhmzy.call;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.SystemClock;
import android.support.v4.content.LocalBroadcastManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Chronometer;
import android.widget.ImageView;
import android.widget.TextView;

import com.hbhmzy.utils.Client;
import com.hbhmzy.utils.EchoClient;
import com.hbhmzy.utils.LocalUDPDataReciever;
import com.hbhmzy.utils.LocalUDPSocketProvider;


public class CallingActivity extends Activity implements View.OnClickListener{
    private static final String TAG = "CallingActivity";
    String symbol,targetname;
    public static AudioManager audioManager;
    boolean is_speaker=true; // true为扬声器打开
    boolean is_mute=true;  // true为静音
    boolean is_online,lisning=true;  //
    ImageView btn_end,btn_speaker,btn_mute;
    TextView textView1;
    Chronometer timer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_calling);
        Intent intent = getIntent();
        Bundle bundle = intent.getExtras();
        symbol = bundle.getString("symbol");
        is_online = bundle.getBoolean("is_online");
        targetname = symbol.substring(symbol.length()-12,symbol.length()-1);

        initview();
        init_manager();
        start_call();
    }

    private void start_call() {
        //一定要开启线程初始化 启动监听
        new Thread(new Runnable() {
            @Override
            public void run() {
                while(lisning){
                    if(is_online){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textView1.setVisibility(View.GONE);
                                timer.setVisibility(View.VISIBLE);
                                timer.setBase(SystemClock.elapsedRealtime());//计时器清零
                                timer.start();
                            }
                        });
                        // 初始化本地UDP的Socket
                        LocalUDPSocketProvider.getInstance().initSocket();
                        // 启动本地UDP监听（接收数据用的）
                        LocalUDPDataReciever.getInstance().startup();
                        try {
                            EchoClient.getInstance().start();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }finally {
                            lisning=false;
                        }
                    }
                    else {
//                        Log.w(TAG, "waiting ...");
                    }
                }
            }
        }).start();
    }

    private void initview() {
        btn_end = findViewById(R.id.end_call);
        btn_speaker = findViewById(R.id.speaker);
        btn_mute = findViewById(R.id.mute);
        timer= findViewById(R.id.timer);
        TextView textView=findViewById(R.id.calling);
        textView1=findViewById(R.id.wait_call);

        btn_end.setOnClickListener(this);
        btn_mute.setOnClickListener(this);
        btn_speaker.setOnClickListener(this);
        textView.setText(targetname);

    }
    private void init_manager() {
        //获取AudioManager的实例
        audioManager = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE);
        //先判断扬声器是否打开，如果是开的就关闭掉。
        is_speaker=audioManager.isSpeakerphoneOn();
        if(is_speaker){
            is_speaker=false;
            audioManager.setSpeakerphoneOn(is_speaker);
        }
        Log.e(TAG, String.valueOf(is_speaker));

        //判断麦克风是否静音，如果是关闭就打开。
        is_mute=audioManager.isMicrophoneMute();
        if(is_mute){
            is_mute=false;
            audioManager.setMicrophoneMute(is_mute);
        }
        Log.e(TAG, String.valueOf(is_mute));

        //注册本地广播接收器 接收"hbhmzy.reject"类型广播
        IntentFilter intentFilter_rej = new IntentFilter();
        intentFilter_rej.addAction("hbhmzy.reject");
        LocalReceiver_rej localReceiver_rej = new LocalReceiver_rej();
        getApplication().registerReceiver(localReceiver_rej, intentFilter_rej);

        //注册本地广播接收器 接收"hbhmzy.acc"类型广播
        IntentFilter intentFilter_acc = new IntentFilter();
        intentFilter_acc.addAction("hbhmzy.acc");
        LocalReceiver_acc localReceiver_acc = new LocalReceiver_acc();
        getApplication().registerReceiver(localReceiver_acc, intentFilter_acc);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.end_call:
            {
                Client.send(symbol + "reject");
                lisning = false;
                finish();
                break;
            }
            case R.id.mute:
            {
                is_mute=!is_mute;
                if(is_mute){
                    btn_mute.setImageDrawable(getResources().getDrawable(R.drawable.mute_press));
                }else{
                    btn_mute.setImageDrawable(getResources().getDrawable(R.drawable.mute));
                }
                audioManager.setMicrophoneMute(is_mute);
                Log.e("OnClick", String.valueOf(is_mute));
                break;
            }
            case R.id.speaker:{
                is_speaker=!is_speaker;
                if(is_speaker){
                    btn_speaker.setImageDrawable(getResources().getDrawable(R.drawable.speaker_press));
                }else{
                    btn_speaker.setImageDrawable(getResources().getDrawable(R.drawable.speaker));
                }
                setSpeakerphoneOn(is_speaker);
                Log.e("OnClick", String.valueOf(is_speaker));
            }
            default: break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EchoClient.getInstance().end();
        LocalUDPDataReciever.getInstance().endreciever();
        timer.stop();
        Log.e(TAG, "end calling");
    }


    //当对方挂断的时候 跳转到主页面
    class LocalReceiver_rej extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            lisning=false;
            finish();
        }
    }

    //当我方拨打电话，对方点击接收后
    class LocalReceiver_acc extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            is_online=true;
        }
    }

    /**
     * 扬声器与听筒切换
     *
     * @param isSpeakerphoneOn
     */
    public void setSpeakerphoneOn(boolean isSpeakerphoneOn) {
        audioManager.setSpeakerphoneOn(isSpeakerphoneOn);
        if (!isSpeakerphoneOn) {
            audioManager.setRouting(AudioManager.MODE_NORMAL, AudioManager.ROUTE_EARPIECE, AudioManager.ROUTE_ALL);
            setVolumeControlStream(AudioManager.STREAM_VOICE_CALL);
            audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);//建立一个音频/视频Voip呼叫。

        }
    }
}
